﻿package com.wabbei.fenxiao.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.AppCustomer;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.PropImg;
import com.taobao.api.domain.Sku;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.IncrementCustomerPermitRequest;
import com.taobao.api.request.IncrementCustomersGetRequest;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.LogisticsOfflineSendRequest;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradeGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.IncrementCustomerPermitResponse;
import com.taobao.api.response.LogisticsOfflineSendResponse;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.webbei.pojo.Orders;
import com.webbei.shoppingCar.service.impl.shoppingCarServiceImpl;

public class MyTaobaoUtil {
	private static String appPath = data.appPath;
	public static TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", data.appkey, data.secret);
	private ApplicationContext ac = new ClassPathXmlApplicationContext(appPath);
	private shoppingCarServiceImpl scs = (shoppingCarServiceImpl) ac.getBean("shoppingCarService");


	public static List<String> incrementNicks() {// 查询应用为哪些用户开通了notify消息服务
		List<String> slist = new ArrayList<String>();
		IncrementCustomersGetRequest req = new IncrementCustomersGetRequest();
		req.setType("notify");
		req.setFields("nick");
		try {
			List<AppCustomer> applist = client.execute(req).getAppCustomers();
			if (applist != null) {
				for (AppCustomer a : applist) {
					slist.add(a.getNick());
				}
			} else {
				return null;
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return slist;
	}

	public static boolean permitIncrement(String sessionkey) {// 为sessionKey用户开通notify消息服务
		IncrementCustomerPermitRequest req = new IncrementCustomerPermitRequest();
		req.setType("notify");
		try {
			IncrementCustomerPermitResponse response = client.execute(req,sessionkey);
			AppCustomer appcus = response.getAppCustomer();
			if (appcus != null) {
				return true;
			} else {
				return false;
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return false;
	}

	public List<Orders> getOrderBytid(Long tid, String sessionKey) {//保存淘宝订单
		List<Orders> orderlist = new ArrayList<Orders>();
		TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
		req.setFields("seller_nick,orders.pic_path,tid,post_fee,buyer_nick,pay_time,seller_memo,orders.title,"
				+ "orders.num_iid,orders.cid,orders.oid,orders.sku_id,orders.num,orders.status,orders.payment,"
				+ "receiver_address,receiver_district,receiver_city,receiver_mobile,receiver_phone,receiver_name,receiver_state,orders.sku_properties_name,buyer_message,orders.refund_id");
		req.setTid(tid);
		com.webbei.pojo.Orders taobaoorder = null;
		try {
			TradeFullinfoGetResponse response = client.execute(req, sessionKey);
			Trade trade = response.getTrade();
			if (trade != null) {
				List<Order> orders = trade.getOrders();
				int ordersize=orders.size();
				for (Order o : orders) {
					Long pp = o.getCid();
					ItemcatsGetRequest itemcatsReq = new ItemcatsGetRequest();
					itemcatsReq.setFields("name");
					itemcatsReq.setCids(pp.toString());
					String productName =client.execute(itemcatsReq).getItemCats().get(0).getName();//产品名称用来匹配发货厂家(产品名称对应到别名alias)
					taobaoorder = new com.webbei.pojo.Orders();
					taobaoorder.setIsShare(0);
					taobaoorder.setOrderContent(trade.getBuyerMessage());//买家留言
					taobaoorder.setUserName(trade.getBuyerNick());
					taobaoorder.setOrderTheme(o.getTitle());
					String cistrict = trade.getReceiverDistrict()==null?"":trade.getReceiverDistrict();
					taobaoorder.setOrderAddress(cistrict+trade.getReceiverAddress());
					System.out.println("address:"+cistrict);
					taobaoorder.setOrderCity(trade.getReceiverCity());
					taobaoorder.setOrderId(o.getOid());
					taobaoorder.setOrderMobilePhone(trade.getReceiverMobile());
					taobaoorder.setReceiveTelephone(trade.getReceiverPhone());
					taobaoorder.setOrderName(trade.getReceiverName());
					//根据买家选择的款式信息来获取产品图片和购买款式
					String propname=o.getSkuPropertiesName();//买家选择的款式信息
					System.out.println(propname);
					if(propname==null||propname.equals("")){//一个产品只有一个款式，无需匹配款式，款式名称直接使用产品名称，订单图片直接采用产品首图
						taobaoorder.setOrderPic(o.getPicPath());
						taobaoorder.setSku(productName);
					}else{
						ItemGetRequest req1=new ItemGetRequest();
						req1.setFields("property_alias,prop_img,sku");
						req1.setNumIid(o.getNumIid());
						Item item = client.execute(req1 , sessionKey).getItem();
						String alias=item.getPropertyAlias();
						String as[]=alias.split(";");
						String property=null;
						for(String s1:as){
							if(s1!=null&&!s1.equals("")){
								if(s1.split(":")[2].equals(propname.split(":")[1])){
									property=s1.split(":")[1];
								}
							}
						}
						if(property==null||property.equals("")){//获取不到属性ID
							taobaoorder.setOrderPic(o.getPicPath());
						}else{
							List<PropImg> propImgs=item.getPropImgs();
							if(propImgs!=null&&!propImgs.toString().equals("[]")&&property!=null){//获取不到属性图片
								int flag=0;
								for(PropImg pi:propImgs){
									if(pi.getProperties().split(":")[1].equals(property)){
										taobaoorder.setOrderPic(pi.getUrl());
										flag=1;
									}
								}
								if(flag==0){
									taobaoorder.setOrderPic("描述："+propname.substring(5)+"（具体图片参考CDR或者备注）");
								}
							}else{
								taobaoorder.setOrderPic("描述："+propname.substring(5)+"（具体图片参考CDR或者备注）");
							}
						}
						//--------------------------------------------------
						//-----------setSku------------//
						List<Sku> skulist=item.getSkus();
						for(Sku s:skulist){
							if(s.getSkuId().toString().equals(o.getSkuId())){
								taobaoorder.setSku(s.getPropertiesName().split(":")[3]);
							}
						}
						//---------------------------------------------------
					}
					taobaoorder.setOrderProductsCount(Integer.parseInt(""+ o.getNum()));
					taobaoorder.setOrderProvince(trade.getReceiverState());
					if (o.getStatus().equals("TRADE_NO_CREATE_PAY") || o.getStatus().equals("WAIT_BUYER_PAY")) {
						taobaoorder.setOrderState(0);
					} else if (o.getStatus().equals("WAIT_SELLER_SEND_GOODS")) {
						taobaoorder.setOrderState(1);
					} else if (o.getStatus().equals("WAIT_BUYER_CONFIRM_GOODS")) {
						taobaoorder.setOrderState(2);
					} else if (o.getStatus().equals("TRADE_FINISHED")) {
						taobaoorder.setOrderState(3);
					}else if(o.getStatus().equals("TRADE_CLOSED_BY_TAOBAO")||o.getStatus().equals("TRADE_CLOSED")){
						taobaoorder.setOrderState(4);
					}else{
						System.out.println("异常订单状态："+o.getStatus());
						taobaoorder.setOrderState(-1);
					}
					taobaoorder.setOrderTime(trade.getPayTime());
					if(ordersize==1){
						taobaoorder.setOrderTotalPrice(Double.parseDouble(o.getPayment())-Double.parseDouble(trade.getPostFee()));
					}else{
						taobaoorder.setOrderTotalPrice(Double.parseDouble(o.getPayment()));
					}
					taobaoorder.setMark(productName);
					taobaoorder.setMemo(trade.getSellerMemo());//卖家备注
					taobaoorder.setTradeId(tid);
					taobaoorder.setPostfee(Double.parseDouble(trade.getPostFee()));
					Integer indusId=scs.getIndusByAlias("%"+productName+"%");
					taobaoorder.setIndustryId(indusId==null?1:indusId);
					taobaoorder.setSellername(trade.getSellerNick());

					//退款单号
					taobaoorder.setRefundid(o.getRefundId());
					orderlist.add(taobaoorder);
				}
			} else {
				String message = response.getMsg();
				System.out.println("读取错误：" + message);
			}
		} catch (ApiException e) {
			
			e.printStackTrace();
		}
		return orderlist;
	}

	public static Map<String,Object> confirmLogistics(Long tradeid,String out_sid,String com_code,String sessionKey){//发货
		Map<String,Object> map=new HashMap<String,Object>();
		LogisticsOfflineSendRequest req=new LogisticsOfflineSendRequest();
		req.setTid(tradeid);
		req.setOutSid(out_sid);
		req.setCompanyCode(com_code);
		try {
			LogisticsOfflineSendResponse response = client.execute(req , sessionKey);
			map.put("ship",response.getShipping());
			map.put("msg", response.getSubMsg());
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return map;
	}
	public void changMemo(Long tradeid,String sessionKey){
		TradeGetRequest req=new TradeGetRequest();
		req.setFields("seller_memo,buyer_message");
		req.setTid(tradeid);
		try {
			Trade t = client.execute(req , sessionKey).getTrade();
			//ServletActionContext.getServletContext().setAttribute(name, object)
			scs.changeMemo(tradeid,t.getBuyerMessage(),t.getSellerMemo());
		} catch (ApiException e) {
			e.printStackTrace();
		}
	}

	public List<Orders> getFullOrderList(String start,String end,String sessionKEY) {//获取start-end的订单(非异步获取)
		//start:"2012-11-28 12:00:00"  end:"2012-12-03 10:00:00"
		List<Orders> orderlist=new ArrayList<Orders>();
		TradesSoldGetRequest req=new TradesSoldGetRequest();
		req.setFields("tid,status");
		try {
			DateFormat format=SimpleDateFormat.getDateTimeInstance();
			req.setStartCreated(format.parse(start));
			req.setEndCreated(format.parse(end));
			List<Trade> trades = client.execute(req , sessionKEY).getTrades();
			if(trades!=null&&!trades.toString().equals("[]")){
				for(Trade trade:trades){
					System.out.println("----------"+trade.getTid());
					System.out.println(trade.getStatus());
					if(!trade.getStatus().equals("WAIT_BUYER_PAY")&&!trade.getStatus().equals("TRADE_CLOSED_BY_TAOBAO")&&!trade.getStatus().equals("TRADE_NO_CREATE_PAY")){
						try{
							for(Orders o:getOrderBytid(trade.getTid(),sessionKEY)){
								orderlist.add(o);
							}
						}catch(Exception e){
							System.out.println("异常订单");
						}
					}
				}
			}
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return orderlist;
	}
	public List<Orders> getFullOrderList(String start,String end) {
		List<Orders> o1=getFullOrderList(start,end,data.sessionKey1);
		List<Orders> o2=getFullOrderList(start,end,data.sessionKey2);
		o1.addAll(o2);
		return o1;
	}
	public boolean alipaySendOut(String trade_no,String logistics_name,String invoice_no,String transport_type){
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "send_goods_confirm_by_platform");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("trade_no", trade_no);
		sParaTemp.put("logistics_name", logistics_name);
		sParaTemp.put("invoice_no", invoice_no);
		sParaTemp.put("transport_type", transport_type);
		String sHtmlText=null;
		try {
			sHtmlText = AlipaySubmit.buildRequest("", "", sParaTemp);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("发货失败");
		}
		if(sHtmlText==null)
			return false;
		else
			return true;
	}

	public static String getSessionKey(String sellname){
		String sessionKey = null;
		if("网贝旗舰店".equals(sellname)){
			sessionKey = data.sessionKey1;
		}
		if("代洋洋816".equals(sellname)){
			sessionKey = data.sessionKey2;
		}
		if("枪声过后".equals(sellname)){
			sessionKey = data.sessionKey3;
		}
		return sessionKey;
	}

	public static void main(){
		//scs.changeMemo(233003592442717L,"我的好人","我是大好人");
		
	}
	public static void main(String[] args) {
		System.out.println(new MyTaobaoUtil().getOrderBytid(355210082469699L, data.sessionKey1));
	}

}
